package com.zenithmind.note.controller;

import com.zenithmind.common.annotation.Log;
import com.zenithmind.common.constant.OperationTypeEnum;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.note.pojo.dto.NoteTagDTO;
import com.zenithmind.note.pojo.query.NoteTagQuery;
import com.zenithmind.note.pojo.query.NoteQuery;
import com.zenithmind.note.pojo.vo.NoteTagVO;
import com.zenithmind.note.pojo.vo.NoteVO;
import com.zenithmind.note.service.NoteTagService;
import com.zenithmind.note.service.NoteTagRelationService;
import com.zenithmind.note.service.NoteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/zenithMind/note/tag")
@RequiredArgsConstructor
@Tag(name = "笔记标签管理")
public class NoteTagController {

    private final NoteTagService tagService;
    private final NoteTagRelationService tagRelationService;
    private final NoteService noteService;
    
    /**
     * 创建标签
     */
    @Log(description = "创建笔记标签", operationType = OperationTypeEnum.ADD)
    @PostMapping("/createTag")
    @Operation(summary = "创建笔记标签")
    public Result<String> createTag(@Validated @RequestBody NoteTagDTO tagDTO) {
        log.info("创建笔记标签：{}", tagDTO);
        return Result.success(tagService.createTag(tagDTO));
    }
    
    /**
     * 更新标签
     */
    @Log(description = "更新笔记标签", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateTag")
    @Operation(summary = "更新笔记标签")
    public Result<Void> updateTag(@Validated @RequestBody NoteTagDTO tagDTO) {
        log.info("更新笔记标签：{}", tagDTO);
        tagService.updateTag(tagDTO);
        return Result.success();
    }
    
    /**
     * 删除标签
     */
    @Log(description = "删除笔记标签", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/deleteTag/{id}")
    @Operation(summary = "删除笔记标签")
    public Result<Void> deleteTag(@PathVariable String id) {
        log.info("删除笔记标签：{}", id);
        tagService.deleteTag(id);
        return Result.success();
    }
    
    /**
     * 获取标签详情
     */
    @Log(description = "获取笔记标签详情", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getTagDetail/{id}")
    @Operation(summary = "获取笔记标签详情")
    public Result<NoteTagVO> getTagDetail(@PathVariable String id) {
        log.info("获取笔记标签详情：{}", id);
        return Result.success(tagService.getTagDetail(id));
    }
    
    /**
     * 分页查询标签列表
     */
    @Log(description = "分页查询笔记标签列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/tagPage")
    @Operation(summary = "分页查询笔记标签列表")
    public Result<PageResult<NoteTagVO>> tagPage(NoteTagQuery query) {
        log.info("分页查询笔记标签列表：{}", query);
        return Result.success(tagService.tagPage(query));
    }
    
    /**
     * 获取用户的标签列表
     */
    @Log(description = "获取用户的笔记标签列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getUserTags")
    @Operation(summary = "获取用户的笔记标签列表")
    public Result<List<NoteTagVO>> getUserTags(@RequestParam(required = false) String userId) {
        log.info("获取用户的笔记标签列表，userId：{}", userId);
        return Result.success(tagService.getUserTags(userId));
    }
    
    /**
     * 获取系统预设标签列表
     */
    @Log(description = "获取系统预设笔记标签列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getSystemTags")
    @Operation(summary = "获取系统预设笔记标签列表")
    public Result<List<NoteTagVO>> getSystemTags() {
        log.info("获取系统预设笔记标签列表");
        return Result.success(tagService.getSystemTags());
    }
    
    /**
     * 获取标签统计信息
     */
    @Log(description = "获取笔记标签统计信息", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getTagStats")
    @Operation(summary = "获取笔记标签统计信息")
    public Result<List<NoteTagVO>> getTagStats(@RequestParam(required = false) String userId) {
        log.info("获取笔记标签统计信息，userId：{}", userId);
        return Result.success(tagService.getTagStats(userId));
    }
    
    /**
     * 获取标签云数据
     */
    @Log(description = "获取标签云数据", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getTagCloud")
    @Operation(summary = "获取标签云数据")
    public Result<List<Map<String, Object>>> getTagCloud(@RequestParam(required = false) String userId) {
        log.info("获取标签云数据，userId：{}", userId);
        return Result.success(tagService.getTagCloud(userId));
    }

    // ==================== 标签关联功能 ====================

    /**
     * 获取笔记的标签列表
     */
    @Log(description = "获取笔记标签", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/note/{noteId}")
    @Operation(summary = "获取笔记的标签列表")
    public Result<List<NoteTagVO>> getNoteTagList(@PathVariable String noteId) {
        log.info("获取笔记标签：noteId={}", noteId);
        return Result.success(noteService.getNoteTagList(noteId));
    }

    /**
     * 设置笔记标签
     */
    @Log(description = "设置笔记标签", operationType = OperationTypeEnum.UPDATE)
    @PostMapping("/note/{noteId}")
    @Operation(summary = "设置笔记标签")
    public Result<Void> setNoteTags(@PathVariable String noteId, @RequestBody List<String> tagIds) {
        log.info("设置笔记标签：noteId={}, tagIds={}", noteId, tagIds);
        tagRelationService.setNoteTags(noteId, tagIds);
        return Result.success();
    }

    /**
     * 根据标签ID查询笔记列表
     */
    @Log(description = "根据标签ID查询笔记列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/{tagId}/notes")
    @Operation(summary = "根据标签ID查询笔记列表")
    public Result<PageResult<NoteVO>> getNotesByTagId(@PathVariable String tagId, NoteQuery query) {
        log.info("根据标签ID查询笔记列表：tagId={}, query={}", tagId, query);

        // 校验参数
        if (query.getCurrent() == null || query.getCurrent() < 1) {
            query.setCurrent(1);
        }
        if (query.getSize() == null || query.getSize() < 1) {
            query.setSize(10);
        }

        // 通过标签关联服务获取笔记ID，然后查询笔记
        List<String> noteIds = tagRelationService.getNoteIdsByTagId(tagId);
        if (noteIds.isEmpty()) {
            return Result.success(PageResult.of(List.of(), 0L, query.getCurrent().longValue(), query.getSize().longValue()));
        }

        // 设置查询条件中的笔记ID列表
        query.setNoteIds(noteIds);
        return Result.success(noteService.notePage(query));
    }

    /**
     * 添加笔记标签
     */
    @Log(description = "添加笔记标签", operationType = OperationTypeEnum.ADD)
    @PostMapping("/note/{noteId}/add/{tagId}")
    @Operation(summary = "添加笔记标签")
    public Result<Void> addNoteTag(@PathVariable String noteId, @PathVariable String tagId) {
        log.info("添加笔记标签：noteId={}, tagId={}", noteId, tagId);
        tagRelationService.addNoteTag(noteId, tagId);
        return Result.success();
    }

    /**
     * 移除笔记标签
     */
    @Log(description = "移除笔记标签", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/note/{noteId}/remove/{tagId}")
    @Operation(summary = "移除笔记标签")
    public Result<Void> removeNoteTag(@PathVariable String noteId, @PathVariable String tagId) {
        log.info("移除笔记标签：noteId={}, tagId={}", noteId, tagId);
        tagRelationService.removeNoteTag(noteId, tagId);
        return Result.success();
    }
}